home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 14891 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.0 KB  |  57 lines

  1. Path: news.clark.net!not-for-mail
  2. From: gusty@clark.net (Harlan Messinger)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Proper use of friend keyword
  5. Date: 2 Apr 1996 15:39:00 GMT
  6. Organization: Clark Internet Services, Inc., Ellicott City, MD USA
  7. Message-ID: <4jrhmk$kdl@clarknet.clark.net>
  8. References: <4jn38u$j9c@holly.ACNS.ColoState.EDU>
  9. NNTP-Posting-Host: explorer.clark.net
  10. Mime-Version: 1.0
  11. Content-Type: TEXT/PLAIN; charset=ISO-8859-1
  12. Content-Transfer-Encoding: 8bit
  13. X-Newsreader: TIN [UNIX 1.3 950726BETA PL0]
  14.  
  15. Corby S. Hudnall (corbyh@holly.ACNS.ColoState.EDU) wrote:
  16. : Hey all, I have a question about how to use the friend keyword.  Consider
  17. : the following example:
  18.  
  19. The purpose of the friend keyword is to allow some or all of the 
  20. member functions of select classes to use directly members of another 
  21. class that are private or protected within that class. When you write
  22.  
  23. :     friend int ABC::GetAValue();
  24.  
  25. inside of the definition of XYZ, you are saying that the body of 
  26. ABC::GetAValue() may directly access protected and private members of an 
  27. XYZ object--that is, members that are ordinarily hidden from outside 
  28. classes--AS members of ABC. It does not create a member function 
  29. GetAValue() within XYZ.
  30.  
  31. Friend functions and classes should be used carefully. The only situation
  32. where one class should be using another class's hidden members is when the
  33. two classes really are working together as a cohesive unit that
  34. theoretically could or should be encapsulated in ONE class, except that
  35. the syntax of the language doesn't permit it, or the classes are not in
  36. one-to-one correspondence. 
  37.  
  38. A definition of XYZ that would use friend properly might be:
  39.  
  40.     class XYZ
  41.     {
  42.         ABC myABC;
  43.     public:    
  44.         XYZ() { }
  45.         ~XYZ() { }
  46.         friend int ABC::GetAValue();
  47.             void processMyABC();
  48.     };
  49.  
  50.     void XYZ::processMyABC()
  51.     {
  52.         myABC.GetAValue();
  53.     }
  54.  
  55. If XYZ wasn't a friend of ABC::GetAValue(), it wouldn't be able to make 
  56. this call to myABC.GetAValue() because ABC::GetAValue() is private to ABC.
  57.